/**
 * 文件系统服务接口定义
 * 抽象化文件系统操作，支持不同环境实现
 */
import {
    FileHandle,
    NovelStructure,
    FileSystemEnvironment,
    FileSystemOptions,
    FileSystemChangeCallback
} from '../../types/fileSystem.ts';

/**
 * 抽象文件系统服务接口
 * 定义所有文件系统操作的基本接口
 */
interface IFileSystemServiceBase {
    // 标识当前运行环境
    readonly environment: FileSystemEnvironment;

    // 权限管理
    checkPermission(handle: FileHandle): Promise<boolean>;
    requestPermission(handle: FileHandle): Promise<boolean>;

    // 基本文件操作
    selectFolder(options?: any): Promise<FileHandle | null>;
    createFolder(parent: FileHandle, name: string): Promise<FileHandle>;
    createFile(parent: FileHandle, name: string, content: string): Promise<FileHandle>;
    rename(handle: FileHandle, newName: string): Promise<boolean>;
    delete(handle: FileHandle): Promise<boolean>;

    // 内容读写
    readTextFile(handle: FileHandle, options?: FileSystemOptions): Promise<string>;
    writeTextFile(handle: FileHandle, content: string, options?: FileSystemOptions): Promise<void>;

    // 结构操作
    listContents(handle: FileHandle): Promise<FileHandle[]>;
    scanNovelStructure(rootFolder: FileHandle): Promise<NovelStructure>;

    // 同步和监控
    beginWatchChanges?(handle: FileHandle, callback: FileSystemChangeCallback): Promise<void>;
    endWatchChanges?(handle: FileHandle): Promise<void>;

    // 创建持久引用（用于保存/恢复会话）
    serializeHandle(handle: FileHandle): string;
    deserializeHandle(serialized: string): Promise<FileHandle | null>;
}

// 导出类型
export type IFileSystemService = IFileSystemServiceBase;

// 创建类型命名空间，以便更好地兼容webpack
export namespace FileSystemTypes {
    export type FileSystemServiceInterface = IFileSystemService;
}

/**
 * 文件系统服务的抽象基类
 * 用于更好地被webpack识别导出
 * 实际项目中使用具体实现类
 */
export abstract class AbstractFileSystemService implements IFileSystemService {
    readonly environment: FileSystemEnvironment;

    constructor(env: FileSystemEnvironment = 'fallback') {
        this.environment = env;
    }

    abstract checkPermission(handle: FileHandle): Promise<boolean>;
    abstract requestPermission(handle: FileHandle): Promise<boolean>;
    abstract selectFolder(options?: any): Promise<FileHandle | null>;
    abstract createFolder(parent: FileHandle, name: string): Promise<FileHandle>;
    abstract createFile(parent: FileHandle, name: string, content: string): Promise<FileHandle>;
    abstract rename(handle: FileHandle, newName: string): Promise<boolean>;
    abstract delete(handle: FileHandle): Promise<boolean>;
    abstract readTextFile(handle: FileHandle, options?: FileSystemOptions): Promise<string>;
    abstract writeTextFile(handle: FileHandle, content: string, options?: FileSystemOptions): Promise<void>;
    abstract listContents(handle: FileHandle): Promise<FileHandle[]>;
    abstract scanNovelStructure(rootFolder: FileHandle): Promise<NovelStructure>;
    abstract serializeHandle(handle: FileHandle): string;
    abstract deserializeHandle(serialized: string): Promise<FileHandle | null>;
} 